<template>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    :rules="rules"
    class="demo-ruleForm"
  >
    <el-form-item label="原密码：" prop="initPass">
      <el-input v-model="ruleForm.initPass" type="password" />
    </el-form-item>
    <el-form-item label="新密码：" prop="updatePass">
      <el-input v-model="ruleForm.updatePass" type="password" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >确认修改</el-button
      >
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { getCurrentInstance, onMounted, reactive, ref } from "vue";
import { ElMessage, type FormInstance } from "element-plus";
import { useLogin } from "@/hooks/loginForm/useLogin";

const { bcrypt } = useLogin();
const { proxy }: any = getCurrentInstance();
const infos = ref<any>({});
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  initPass: "",
  updatePass: "",
});
onMounted(async () => {
  await getInfos()
})

function getInfos(){
  infos.value = JSON.parse(window.sessionStorage.getItem("Infos") || "null");
}

const validateInitPass = (rule: any, value: any, callback: any) => {
  const flag = bcrypt.compareSync(ruleForm.initPass, infos.value.userPass);
  if (value === "") {
    callback(new Error("请输入原密码"));
  } else if (!flag) {
    callback(new Error("原密码错误"));
  } else {
    callback();
  }
};
const validateUpdatePass = (rule: any, value: any, callback: any) => {
  const flags = bcrypt.compareSync(ruleForm.updatePass, infos.value.userPass);
  if (value === "") {
    callback(new Error("新密码不能为空"));
  } else if (flags) {
    callback(new Error("新密码与原密码相同"));
  } else {
    callback();
  }
};

const rules = reactive({
  initPass: [{ validator: validateInitPass, trigger: "blur" }],
  updatePass: [{ validator: validateUpdatePass, trigger: "blur" }],
});

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid) => {
    if (valid) {
      proxy.$http
        .post("/user/upPass/" + infos.value.id, {
          userPass: ruleForm.updatePass,
        })
        .then(async (res: any) => {
          ElMessage.success(res.message);
          ruleForm.initPass = ''
          ruleForm.updatePass = ''
          window.sessionStorage.setItem("Infos", JSON.stringify(res.data));
          await getInfos()
        });
    } else {
      return false;
    }
  });
};
</script>

<style lang="less" scoped>
.passBox {
  display: flex;
  flex-direction: column;
  &-init {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    .el-input {
      width: 400px;
    }
  }
  .el-button {
    width: 80px;
  }
}
</style>
